package com.zhang.modules.video.service.impl;

import com.zhang.CosService;
import com.zhang.common.jpa.entity.DTO;
import com.zhang.common.jpa.service.impl.BaseServiceImpl;
import com.zhang.constants.CacheConstant;
import com.zhang.exception.exception.NormalException;
import com.zhang.modules.file.entity.CosFileInfo;
import com.zhang.modules.file.service.ICosFileService;
import com.zhang.modules.file.service.impl.CosFileService;
import com.zhang.modules.video.entity.VideoBasicInfo;
import com.zhang.modules.video.rep.VideoBasicRep;
import com.zhang.modules.video.service.IVideoBasicService;
import com.zhang.service.RedisService;
import org.aspectj.weaver.ast.Var;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class VideoBasicService extends BaseServiceImpl<VideoBasicRep, VideoBasicInfo,String> implements IVideoBasicService {

    private CosService cosService;

    private ICosFileService cosFileService;

    private RedisService redis;

    public VideoBasicService(CosService cosService, ICosFileService cosFileService, RedisService redis) {
        this.cosService = cosService;
        this.cosFileService = cosFileService;
        this.redis = redis;
    }

    @Override
    public <R extends DTO> R convert2DtoSingle(VideoBasicInfo orginInfo) {
        return (R) orginInfo;
    }

    @Override
    public String getVideoUrl(String id) {

        if (!redis.hasKey(CacheConstant.VIDEO_URL_PREFIX+id)){
            //查询视频基本信息
            VideoBasicInfo videoBasicInfo = get(id);
            if (videoBasicInfo == null) throw new NormalException("视频状态异常");

            //获取文件信息
            CosFileInfo cosFileInfo = cosFileService.get(videoBasicInfo.getFileKey());

            //调用cos服务器获取远程访问地址
            String objectUrl = cosService.getObjectUrl(cosFileInfo.getObjectKey(), cosFileInfo.getBucketName());

            //缓存三个小时
            redis.setCacheObject(CacheConstant.VIDEO_URL_PREFIX+id,objectUrl,60*60*3L, TimeUnit.SECONDS);
        }

        return redis.getCacheObject(CacheConstant.VIDEO_URL_PREFIX+id);
    }
}
